<?php
// 素材管理
// https://developers.weixin.qq.com/doc/offiaccount/Asset_Management/New_temporary_materials.html

namespace JyWxThird\Init\Mp;

use JyWxThird\Kernel\Http;

trait Media
{
  /**
   * 获取临时素材
   *
   * @param string $media_id 媒体ID
   * @param int    $kind     素材类型，0=临时，1=永久
   * @return array|bool
   */
  public function mediaGet($media_id, $kind = 0)
  {
    if ($kind == 0) {
      $url = $this->domainUrl . "/cgi-bin/media/get?access_token=" . $this->get_access_token() . '&media_id=' . $media_id;
      $res = Http::httpGet($url);
      if (isset($res['errcode']) && $res['errcode'] != 0) {
        $this->setError($res);
        return false;
      }
      return $res;
      
    } else {
      $url   = $this->domainUrl . "/cgi-bin/material/get_material?access_token=" . $this->get_access_token();
      $param = [
        'media_id' => $media_id,
      ];
      $res   = Http::httpPostJson($url, $param);
      
      if (isset($res['errcode']) && $res['errcode'] != 0) {
        $this->setError($res);
        return false;
        // 视频素材
      } else if (is_array($res) && isset($res['title'])) {
        return $this->handleReturn(Http::httpPostJson($url, $param), 'title');
      } else {
        return Http::httpPostJson($url, $param);
      }
    }
  }
  
  /**
   * 获取素材总数
   */
  public function mediaGetCount()
  {
    $url = $this->domainUrl . "/cgi-bin/material/get_materialcount?access_token=" . $this->get_access_token();
    return $this->handleReturn($res = Http::httpGet($url), 'voice_count');
  }
  
  /**
   * 获取素材列表，永久素材有效
   *
   * @param string $type  素材的类型，图片（image）、视频（video）、语音 （voice）、图文（news）
   * @param int    $page  页码，从1开始
   * @param int    $limit 每页返回的数量
   * @return array|bool
   */
  public function mediaGetList($type = 'image', $page = 1, $limit = 20)
  {
    $page  = max(1, $page);
    $param = [
      'type'   => $type,
      'offset' => ($page - 1) * $limit,
      'count'  => $limit,
    ];
    $url   = $this->domainUrl . "/cgi-bin/material/batchget_material?access_token=" . $this->get_access_token();
    return $this->handleReturn(Http::httpPostJson($url, $param), 'total_count');
  }
  
  /**
   * 删除素材，只有永久的素材可以删除
   *
   * @param string $media_id 媒体ID
   * @return array|bool
   */
  public function mediaDel($media_id)
  {
    $url   = $this->domainUrl . "/cgi-bin/material/del_material?access_token=" . $this->get_access_token();
    $param = [
      'media_id' => $media_id,
    ];
    return $this->handleReturn(Http::httpPostJson($url, $param));
  }
  
  /**
   * 上传图片素材
   *
   * @param string $filePath 文件路径
   * @param int    $kind     素材类型，0=临时，1=永久
   * @return false|void
   */
  public function mediaUploadImage($filePath, $kind = 0)
  {
    return $this->mediaUpload($filePath, 'image', $kind);
  }
  
  /**
   * 上传语音素材
   *
   * @param string $filePath 文件路径
   * @param int    $kind     素材类型，0=临时，1=永久
   * @return false|void
   */
  public function mediaUploadVoice($filePath, $kind = 0)
  {
    return $this->mediaUpload($filePath, 'voice', $kind);
  }
  
  /**
   * 上传视频素材
   *
   * @param string $filePath 文件路径
   * @param int    $kind     素材类型，0=临时，1=永久
   * @param int    $info     视频信息，只有永久素材有效
   * @return false|void
   */
  public function mediaUploadVideo($filePath, $kind = 0, $info = [])
  {
    return $this->mediaUpload($filePath, 'video', $kind, $info);
  }
  
  /**
   * 上传缩略图素材
   *
   * @param string $filePath
   * @param int    $kind 素材类型，0=临时，1=永久
   * @return false|void
   */
  public function mediaUploadThumb($filePath, $kind = 0)
  {
    return $this->mediaUpload($filePath, 'thumb', $kind);
  }
  
  /**
   * 素材上传
   *
   * @param string $filePath  文件路径
   * @param string $type      素材类型，图片（image），语音（voice），视频（video），缩略图（thumb）
   * @param string $kind      素材类型，0=临时，1=永久
   * @param string $videoInfo 视频信息，上传视频专用
   * @return false|void
   */
  public function mediaUpload($filePath, $type = 'image', $kind = 0, $videoInfo = [])
  {
    if (!in_array($type, ['image', 'voice', 'video', 'thumb'])) {
      $this->setError('上传类型不被允许');
      return false;
    } else if (!file_exists($filePath)) {
      $this->setError('要上传的文件不存在，请检查路径是否有误: ' . $filePath);
      return false;
    }
    
    if ($kind == 0) {
      $url = $this->domainUrl . "/cgi-bin/media/upload";
    } else {
      $url = $this->domainUrl . "/cgi-bin/material/add_material";
    }
    $param = [
      'type'         => $type,
      'access_token' => $this->get_access_token(),
    ];
    if ($type == 'video') {
      $param['description'] = json_encode($videoInfo, JSON_UNESCAPED_UNICODE);
    }
    
    $res = Http::httpUpload($url, ['media' => $filePath], $param);
    
    return $this->handleReturn($res, 'media_id', 'thumb_media_id');
  }
  
  /**
   * 上传图文消息内的图片获取URL
   *
   * @param string $filePath 文件路径
   */
  public function mediaUploadImageText($filePath)
  {
    if (!file_exists($filePath)) {
      $this->setError('要上传的图片不存在，请检查路径是否有误: ' . $filePath);
      return false;
    }
    $url   = $this->domainUrl . "/cgi-bin/media/uploadimg";
    $param = [
      'access_token' => $this->get_access_token(),
    ];
    return $this->handleReturn(Http::httpUpload($url, ['media' => $filePath], $param), 'url');
  }
  
  /**
   * 新建图片群发消息(开放平台的权限没有这一块)
   *
   * @param array $articles 图文章节
   * @return array|bool
   */
  public function mediaCreateImageTextMsg($articles)
  {
    // 如果传的是单个，需要转成多个
    if (isset($articles['title'])) {
      $articles = [$articles];
    }
    $url = $this->domainUrl . "/cgi-bin/material/add_news?access_token=" . $this->get_access_token();
    $res = Http::httpPostRaw($url, json_encode(['articles' => $articles], JSON_UNESCAPED_UNICODE));
    return $this->handleReturn($res, 'media_id');
  }
}
